<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '支付密码',
    backgroundColor: '#f5f5f5',
  },
}
</route>
<template>
  <view class="container">
    <!-- 密码输入提示 -->
    <view class="tip">请输入6位支付密码</view>

    <!-- 密码输入框 -->
    <wd-password-input
      v-model="password"
      :focused="showKeyboard"
      :maxlength="6"
      @focus="showKeyboard = true"
    />
    <!-- 数字键盘 -->
    <wd-number-keyboard
      v-model="password"
      v-model:visible="showKeyboard"
      :maxlength="6"
      @blur="showKeyboard = false"
    />
  </view>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { balancePay } from '@/service/user/info'
import { useToast } from 'wot-design-uni'
const toast = useToast()
// 密码输入相关
const password = ref<string>('')
const showKeyboard = ref<boolean>(true)
const orderNo = ref<string>()

onLoad((options) => {
  console.log(options)

  orderNo.value = options?.orderNo || ''
})
// 监听密码输入完成
watch(password, (newVal) => {
  if (newVal.length === 6) {
    handlePay()
  }
})

// 处理支付逻辑
const handlePay = async () => {
  try {
    showKeyboard.value = false // 隐藏键盘
    if (orderNo.value === '' || orderNo.value === undefined) return toast.show('订单号不能为空')
    // 调用支付接口
    toast.loading({ msg: '支付中...' })
    const { code, data, message } = await balancePay({
      password: password.value,
      orderNo: orderNo.value,
    })
    toast.close()

    if (code === 200 && data) {
      uni.navigateTo({ url: `/pages/pay/paySuccess?orderId=${data}` })
    } else {
      toast.show(message)
    }
  } catch (e) {
    showError()
    toast.show('支付异常')
  } finally {
    showError()
  }
}

// 显示错误提示
const showError = () => {
  password.value = '' // 清空密码
  showKeyboard.value = true // 重新聚焦输入框
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;

  background: #f5f5f5;
}

.tip {
  margin: 60rpx 0;
  font-size: 32rpx;
  color: #666;
  text-align: center;
}
/* 调整密码输入框样式 */
:deep(.wd-password-input) {
  margin-top: 80rpx;

  li {
    width: 80rpx;
    height: 80rpx;
    margin: 0 20rpx;
    border-radius: 16rpx;
  }
}
</style>
